﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.RegularExpressions;

namespace Wilke.SharePoint.Tools
{   
    [Serializable]
    public class WebConfigModification
    {
        public string Owner { get; set; }
        public string Name { get; set; }
        public string Path { get; set; }
        private string configValue;
        public string Value 
        {
            get { return configValue; }
            set { configValue = FixUpValue(value); } 
        }
        public int Sequence { get; set; }
        public WebConfigModificationType Type { get; set; }
        public bool Checked { get; set; }
        public string PreviousAttributeValue { get; set; }        

        internal WebConfigModification Clone()
        {
            WebConfigModification clone;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                BinaryFormatter binaryFormatter = new BinaryFormatter();
                binaryFormatter.Serialize(memoryStream, this);
                memoryStream.Position = 0;
                clone = (WebConfigModification)binaryFormatter.Deserialize(memoryStream);
            }

            return clone;
        }

        public override bool Equals(object obj)
        {
            WebConfigModification modification = obj as WebConfigModification;
            return ((((modification != null) && this.Name.Equals(modification.Name)) && (this.Path.Equals(modification.Path) && this.Value.Equals(modification.Value))) && (this.Type.Equals(modification.Type) && this.Owner.Equals(modification.Owner)));
        }

        public override int GetHashCode()
        {
            return (this.Name + this.Path).GetHashCode();
        }

        private static string FixUpValue(string value)
        {
            Regex regex = new Regex(@">([^>]*)<");

            MatchCollection matchCollection = regex.Matches(value);

            foreach (Match match in matchCollection)
            {
                value = value.Replace(match.Value, "><");
            }
            
            return value;
        }

    }   
}
